package com.atguigu04.threadsafemore.singleton;

import java.lang.reflect.InaccessibleObjectException;

/**
 * ClassName: PersonTest
 * Description:
 *
 * @Author liu
 * @Create 2024/11/16 17:20
 * @Version 1.0
 */
public class BankTest {
    static Bank b1 = null;
    static Bank b2 = null;
    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                b1 = Bank.getInstance();
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                b2 = Bank.getInstance();
            }
        }.start();

         System.out.println(b1);
        System.out.println(b2);
        System.out.println(b1 == b2);


}

static class Bank{
    private Bank(){}

    private static volatile Bank instance = null;

    //实现线程安全的方式1
   /* public static synchronized Bank getInstance(){
        if(instance == null){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            instance = new Bank();
        }
    return instance;
    }
    */
    //实现线程安全的方式2
/*    public static Bank getInstance(){
        synchronized (Bank.class) {
            if(instance == null){

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                instance = new Bank();
            }

        }
        return instance;
    }
    */

     //实现线程安全的方式3:相较于方式1和方式2来讲，效率更高。为了避免出现指令重排，需要将instance声明为volatile
    public static Bank getInstance(){
        if(instance == null) {
            synchronized (Bank.class) {
                if (instance == null) {

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    instance = new Bank();
                }

            }
        }
        return instance;
    }

}

}
